<template>
	<view class="container">
		<view class="course-item">
			<view class="course-content">
				<view class="img-wrapper" v-if="proInfo.pic">
					<image class="pic" :src="proInfo.pic"></image>
				</view>
				<view class="uni-flex uni-row banner" style="-webkit-justify-content: space-between;justify-content: space-between;">
					<text class="title" >{{proInfo.name}}</text>
					<text class="price"><span class="money">{{proInfo.need_money}}</span>元</text>
				</view>
				<text class="introduce">
					{{proInfo.describe}}
				</text>
				<view class="detail-desc">
					<rich-text :nodes="proInfo.content"></rich-text>
				</view>
			</view>
			<button v-if="hasLogin" type="primary" @click="add_user()">{{addBtnTitle}}</button>
			<button v-if="!hasLogin" type="primary" @click="navTo()">请先登录</button>
		</view>
		
		<view class="record-section icon">
			<view v-for="(item,index) in course_record" class="mix-list-cell b-b" hover-class="cell-hover"  hover-stay-time="50">
				<text class="cell-tit clamp">{{item.account}}</text>
				<text >进度:</text>
				<slider v-if="item.number_per_max" @change="sliderChange" class="cell-tit slider clamp" :value="item.number_per" :max="item.number_per_max" disabled show-value block-size="10"  />
				<!-- <uni-badge type="error" text="0">
				</uni-badge> -->
				<button class="mini-btn" v-if="item.is_payed && (item.status == 0 || item.status == 3)" type="primary" @click="start_study(item.id)">开始</button>
				<button class="mini-btn" v-if="!item.is_payed && (item.status == 0 || item.status == 3)" type="primary" @click="start_pay(item.id)">支付宝</button>
				<button class="mini-btn" v-if="item.status == 1" loading="true" type="default">学习中...</button>
				<button class="mini-btn" v-if="item.status == 2" disabled="true" plain="true" type="default">完成</button>
			</view>
		</view>
		
		<uni-popup ref="login"  type="dialog">
			<view class="uni-tip">
				<text class="uni-tip-title">登录</text>
				<text class="uni-tip-content">使用扫描，或保存二维码识别</text>
				<view class="uni-image uni-center">
				<tki-qrcode :val="login_qr" :loadMake="true" :onval="true" :size="350"/>
				</view>
				<view class="uni-tip-group-button">
					<text class="uni-tip-button" @click="popup_cancel('login')">取消</text>
					<text class="uni-tip-button" @click="popup_cancel('login')">完成</text>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import listCell from '@/components/mix-list-cell';
import uniPopup from '@/components/uni-popup/uni-popup.vue';
import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue";
import {mapState, mapMutations} from 'vuex';
import request_async from '../../common/request_async.js';
export default {
	components: {
		listCell,
		uniPopup,
		tkiQrcode
	},
	computed: {
		...mapState(['hasLogin','userInfo'])
	},
	data() {
		return {
			so: 'websocket ob', 
			user_id: 0,
			course_id : 0,
			proInfo: {
				title: "新品上市，全场满199减50",
				time: "昨天 12:30",
				readed: false,
				content: `
					loading...
					`,
			},
			course_record: [
				{account: '账号名', phone: '手机号'}
			],
			addBtnTitle : '点击报名',
			pay_reg_id : 0,
			pay_jumpUrl : '',
			login_qr: '',
		};
	},
	mounted () {
		// 初始化
	},
	onShow() {
		uni.setNavigationBarTitle({
		    title: '课程报名'
		});
		
	},
	watch:{
		user_id :{
			handler(newVal, oldVal) {
				if(newVal != 0){
					this.init(newVal);
				}
				
			},  
			immediate: true,  
			deep: true
		}
	},
	methods:{
		init: function (userId) {
			if(typeof(WebSocket) === "undefined"){
				alert("您的浏览器不支持socket")
				return false;
			}
			
			console.log('this.$wshost '+this.$wshost);
			var so = uni.connectSocket({
			    url: this.$wshost,
				success : (res)=> {
					console.log('success：' + res);
				},
				fail : (res)=> {
					console.log('fail：' + res);
				},
			    complete: (res)=> {
					console.log('complete：' + res);
				}
			});
			console.log('this.userInfo ', this.userInfo, this.userInfo.id)
			uni.onSocketOpen(function (res) {
				console.log('WebSocket连接已打开！');
				console.log('finish inited', userId);
				so.send({data: JSON.stringify({
					'action': 'init_user',
					'user_id': userId,
					'task_class': 'OrderAlipayTask'
				})});
			});
			uni.onSocketError(function (res) {
				console.log('WebSocket连接打开失败，请检查！');
			});
			var that = this;
			uni.onSocketMessage(function (res) {
				console.log('收到服务器内容：' + res.data);
				uni.showLoading({
					title: '正在生成二维码, 请稍后...'
				});
				var dataArr = {}
				try{
					dataArr = JSON.parse(res.data);
					console.log('dataArr 1', dataArr);
				}catch(e){ console.log(e)}
				console.log('dataArr', dataArr);
				if(dataArr.dealTask == 'OrderAlipayTask'){
					that.login_qr = dataArr.qr;
					that.$refs['login'].open()
					
				}
				uni.hideLoading();
			});
			uni.onSocketClose(function (res) {
			  console.log('WebSocket 已关闭！');
			});
			
		},
		add_user(){
			var nitem = {id: this.proInfo.id, name: this.proInfo.name,};
			console.log('nitem: ', nitem)
			uni.navigateTo({
				url: `/pages/course/form?data=${JSON.stringify(nitem)}`
			})
		},
		//开启学习
		async start_study(regId){
			console.log('start_study regId ' + regId);
			var res = await request_async({
				name: 'courseuser.learn',
				method: 'POST',
				data: {reg_id: regId},
			})
			console.log(res);
			if (res.code === 0) {
				this.$api.msg('开始学习');
				var records = [];
				this.course_record.forEach(item=>{
					if(item.id == regId){
						item.status = 1;
					}
					console.log(item)
					records.push(item);
				})
				this.course_record = records;
				// uni.navigateTo({
				// 	// url: "/pages/course/study?id=" + res.data.id
				// })
			} else {
				this.$api.msg(res.msg);
			}
		},
		popup_qr(type) {
			this.$nextTick(() => {
				this.$refs[type].open()
			})
		},
		popup_cancel(type) {
			this.$refs[type].close()
		},
		popup_pay_ok(){
			this.start_study(this.pay_reg_id);
			this.popup_cancel('pay');
		},
		//开如支付
		async start_pay(regId){
			this.pay_reg_id = regId;
			// this.popup_pay_qr();
			// return false;
			uni.showLoading({
				title: '正在生成二维码, 请稍后...'
			});
			console.log('start_pay regId ' + regId);
			var res = await request_async({
				// name: 'pay.ali_add',
				name: 'pay.xorpay_add',
				method: 'POST',
				data: {reg_id: regId},
			})
			uni.hideLoading();
			console.log('pay return', res);
			if (res.code === 0) {
				// res.data.qr 
				this.popup_qr('pay');
				// alipays://platformapi/startapp?appId=20000067&url=http%3A%2F%2Fxorpay.com
				this.pay_jumpUrl = res.data.qr
				if(res.data.pay_type == 'alipay'){
					//this.pay_jumpUrl = 'alipays://platformapi/startapp?appId='+res.data.ali_appid+'&url=' + res.data.qr;
				}else{
					
				}
				console.log('jump to ', this.pay_jumpUrl);
				
				// uni.navigateTo({
				// 	url: this.pay_jumpUrl
				// })
				
			} else {
				this.$api.msg(res.msg);
			}
		},
		navTo(url, toBar = false){
			if(!this.hasLogin){
				url = '/pages/course/login';
			}
			if (toBar) {
				console.log('switch')
				uni.switchTab({
					url: url,
					error(error) {
						console.log(error)
					}
				})
			} else {
				uni.navigateTo({  
					url
				})  
			}
		}
	},
	async onLoad(options) {
		if(options.id == undefined){
			uni.navigateTo({
				url: `/pages/course/index`
			})
			return false;
		}
		
		var res = await request_async({
			name: 'course.detail',
			method: 'POST',
			data: {id : options.id}
		})
		if(res.code != 0 || res.data == null){
			return false;
		}
		this.proInfo = res.data;
		console.log('hasLogin: ', this.hasLogin)
		console.log('detail proInfo: ', this.proInfo)
		if(this.proInfo.content == null){
			this.proInfo.content = '';
		}
		
		//报表记录列表
		var res = await request_async({
			name: 'courseuser.list',
			method: 'POST',
			data: {course_id : options.id, phone: this.userInfo.phone}
		})
		if(res.code != 0 || res.data == null){
			return false;
		}
		var records = [];
		var need_point = this.proInfo.need_point;
		res.data.data.forEach(item=>{
			// var fper = Math.round(parseInt(item.finish_per)/parseInt(need_point));
			item.number_per = item.finish_per;
			item.number_per_max = need_point;
			records.push(item);
		})
		this.user_id = this.userInfo.id;
		this.course_record = records;
		console.log('detail course_record: ', this.course_record)
		if(records.length > 0){
			this.addBtnTitle = '追加报名';
		}
		
	}
};
</script>

<style lang="scss">
page {
	background: $page-color-base;
	/* padding-bottom: 160upx; */
}
.icon-you {
	font-size: $font-base + 2upx;
	color: #888;
}

.course-item{
		display: flex;
		flex-direction: column;
		padding-left: 30upx;
		background: #fff;
		margin-top: 16upx;
		.course-content {
			width: 710upx;
			padding: 0 24upx;
			background-color: #fff;
			border-radius: 4upx;
		}
		.banner {
			flex-grow: 2;
			display: flex;
			height: 90upx;
			font-size: 30rpx;
			align-items: center;
			.title {
				color: #303133;
			}
			.price {
				float: right;
				font-weight: bold;
			}
			.money {
				color: red;
			}
		}
		.img-wrapper {
			width: 100%;
			height: 260upx;
			position: relative;
		}
		.pic {
			display: block;
			width: 100%;
			height: 100%;
			border-radius: 6upx;
		}
		.cover {
			display: flex;
			justify-content: center;
			align-items: center;
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, .5);
			font-size: 36upx;
			color: #fff;
		}
		.introduce {
			display: inline-block;
			padding: 16upx 0;
			font-size: 28upx;
			line-height: 38upx;
		}
		.bot {
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 90upx;
			font-size: 24upx;
			color: #707070;
			position: relative;
		}
		.more-icon {
			font-size: 32upx;
		}	
	}
	
/*  详情 */
.detail-desc {
	background: #fff;
	margin-top: 16upx;
	.d-header {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 80upx;
		font-size: $font-base + 2upx;
		color: $font-color-dark;
		position: relative;

		text {
			padding: 0 20upx;
			background: #fff;
			position: relative;
			z-index: 1;
		}
		&:after {
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translateX(-50%);
			width: 300upx;
			height: 0;
			content: '';
			border-bottom: 1px solid #ccc;
		}
	}
}

.record-section{
	padding: 30upx 0 0;
	margin-top: 20upx;
	background: #fff;
	border-radius:10upx;
	.mini-btn {
	    margin-right: 10rpx;
		font-size: $font-base - 8upx;;
	}
	.sec-header{
		display:flex;
		align-items: center;
		font-size: $font-base;
		color: $font-color-dark;
		line-height: 40upx;
		margin-left: 30upx;
		.yticon{
			font-size: 44upx;
			color: #5eba8f;
			margin-right: 16upx;
			line-height: 40upx;
		}
	}
	.h-list{
		white-space: nowrap;
		padding: 30upx 30upx 0;
		image{
			display:inline-block;
			width: 160upx;
			height: 160upx;
			margin-right: 20upx;
			border-radius: 10upx;
		}
	}
	
	.icon .mix-list-cell.b-b:after{
		left: 90upx;
	}
	.mix-list-cell{
		display:flex;
		align-items:baseline;
		padding: 20upx $page-row-spacing;
		line-height:60upx;
		position:relative;
		
		&.cell-hover{
			background:#fafafa;
		}
		&.b-b:after{
			left: 30upx;
		}
	
		.cell-icon{
			align-self:center;
			width:56upx;
			max-height:60upx;
			font-size:38upx;
		}
		.cell-more{
			align-self: center;
			font-size:30upx;
			color:$font-color-base;
			margin-left:$uni-spacing-row-sm;
		}
		.cell-tit{
			flex: 1;
			font-size: $font-base;
			color: $font-color-dark;
		}
		.slider{
			margin: 0 3px 0 5px;
		}
		.cell-tip{
			font-size: $font-sm+2upx;
			color: $font-color-light;
		}
	}
}
/* 提示窗口 */
.uni-tip {
	/* #ifndef APP-NVUE */
	display: flex;
	flex-direction: column;
	/* #endif */
	padding: 15px;
	width: 300px;
	background-color: #fff;
	border-radius: 10px;
}

.uni-tip-title {
	margin-bottom: 10px;
	text-align: center;
	font-weight: bold;
	font-size: 16px;
	color: #333;
}

.uni-tip-content {
	font-size: 14px;
	color: #666;
	text-align: center;
}

.uni-tip-group-button {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	margin-top: 20px;
}

.uni-tip-button {
	flex: 1;
	text-align: center;
	font-size: 14px;
	color: #3b4144;
}
.qr_size{
	width: 250px;
}
</style>
